<template>
    <div class="users">
        <div>
            <auth-group-list :select="true" :show-share="false" :sub-height="135" @data-list="getAuthGroupList" @change="changeAuthGroup"></auth-group-list>
        </div>
        <div>
            <div class="page-action-btn">
                <el-button type="primary" v-if="UIAuth._api_admin_users_post" @click="showAdd()">添加用户</el-button>
                <el-button type="warning" v-if="UIAuth._api_admin_users_put" @click="showEdit()">修改</el-button>
                <p-confirm-btn v-if="UIAuth._api_admin_users_delete" @confirm="del"></p-confirm-btn>
            </div>
            <div v-if="UIAuth._api_admin_users_paginate_get">
                <p-table ref="pTable" v-loading="loading" :data="dataList" :sub-height="175" :show-paginate="true" v-model="paginate" @row-click="rowClick" @row-dblclick="showEdit"
                    @row-clear="rowClear" @selection-change="selectionChange" @paginate="getList">
                    <el-table-column prop="account.nickname" label="昵称" width="200"></el-table-column>
                    <el-table-column prop="account.account" label="账号" min-width="160"></el-table-column>
                    <el-table-column prop="account.account_type" label="账号类型" width="95">
                        <template v-slot="{ row }">
                            <user-type :type="row.account.account_type"></user-type>
                        </template>
                    </el-table-column>
                    <el-table-column label="账号权限" min-width="120">
                        <template v-slot="{ row }">
                            <div class="users-roles-list" v-if="row.account.account_type == accountType.SYSTEM_ADMIN">
                                <div>
                                    {{getAccountLabel(row.account.account_type)}}
                                </div>
                            </div>
                            <div class="users-roles-list">
                                <div v-for="(item,index) in getRolesLabel(row.user.roles)" :key="index">
                                    {{item}}
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="account.username" label="姓名" width="80"></el-table-column>
                    <el-table-column prop="account.id_card" label="身份证号码" width="170"></el-table-column>
                    <el-table-column prop="account.mobile" label="手机" width="120"></el-table-column>
                    <el-table-column prop="account.sex" label="性别" width="50">
                        <template v-slot="{ row }">
                            <sex :sex="row.account.sex"></sex>
                        </template>
                    </el-table-column>
                    <el-table-column prop="user.login_ip" label="登录IP" min-width="130"></el-table-column>
                    <el-table-column prop="user.login_time" label="最后登陆时间" width="160">
                        <template v-slot="{ row }">
                            <div>{{ utils.GolangDateTime(row.user.login_time) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="user.reg_time" label="添加时间" width="160">
                        <template v-slot="{ row }">
                            <div>{{ utils.GolangDateTime(row.user.reg_time) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="user.remarks" label="备注" min-width="360"></el-table-column>
                </p-table>
            </div>
        </div>
        <p-el-dialog v-model="showDialog" :title="getTitle" width="40%" @close="dialogClose" @confirm="isEdit ? edit() : add()" :ok-text="isEdit ? '修改' : '添加'">
            <el-form :model="params" status-icon :rules="paramsRules" ref="elForm" label-width="120px">
                <el-form-item label="账号类型" v-if="accountRow">
                    <user-type :type="accountRow.account_type"></user-type>
                </el-form-item>
                <el-form-item label="所属权限组" prop="auth_group_id">
                    <el-select v-model="params.auth_group_id" placeholder="请选择" @change="selectAuthFGroup">
                        <!--<el-option label="请选择" value=""></el-option>-->
                        <el-option v-for="item in authGroupList" :label="item.title" :value="item.id" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="用户账号" v-if="!isEdit">
                    <select-account v-model="params.account_id" @change="changeAccount"></select-account>
                </el-form-item>

                <el-form-item label="权限角色" v-show="accountRow && accountRow.account_type < accountType.SYSTEM_ADMIN">
                    <el-select v-model="params.roles" placeholder="请选择权限角色" multiple style="width:100%;">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.role_name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input type="textarea" :row="5" v-model="params.remarks" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
        </p-el-dialog>
    </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, toRefs } from "vue";
import { useStore } from "vuex";
import { IPaginate, defaultPaginate } from "@/lib/IApp";
import http from "@/lib/http/http";
import PConfirmBtn from "@/components/PConfirmBtn.vue";
import message from "@/lib/message";
import utils from "@/lib/utils";
import AuthGroupList from "@/components/auth/AuthGroupList.vue";
import PTable from "@/components/PTable.vue";
import PElDialog from "@/components/PElDialog.vue";
import UserType from "@/components/user/UserType.vue";
import Sex from "@/components/Sex.vue";
import SelectAccount from "@/components/account/SelectAccount.vue";
import AccountType, { getAccountLabel } from "@/lib/user/AccountType";
const ParamsRules: any = {
    auth_group_id: [
        {
            required: true,
            message: "选择所属权限组",
            trigger: ["blur", "change"],
        },
    ],
};
/**
 * state 数据类型
 */
interface IState {
    loading: boolean;
    dataList: any[]; // 数据列表
    paginate: IPaginate; // 分页数据
    showDialog: boolean; // 是否显示 添加编辑窗口
    isEdit: boolean; // 是否修改
    params: any; // http 请求参数
    paramsRules: any; // 参数校验
    tableRow: any; // 单选选择的行内容
    tableRows: any[]; // 多选选择的行内容
    authGroupList: any[]; // 菜单权限组列表
    selectAuthGroup: any; // 选择的菜单权限组
    search: any; // 查询条件
    rolesList: any[]; // 权限角色列表
    rolesAllList: any[]; // 全部权限角色列表
    accountRow: any; // 选择的用户账号
}
export default defineComponent({
    name: "Users",
    components: {
        PElDialog,
        PConfirmBtn,
        AuthGroupList,
        PTable,
        UserType,
        Sex,
        SelectAccount,
    },
    setup() {
        const store = useStore();
        const { UIAuth, bodySize } = toRefs(store.state);
        const accountType = AccountType;
        const pTable: any = ref<any>();
        const elForm: any = ref<any>();
        const state = reactive<IState>({
            loading: false,
            dataList: [], // 数据列表
            paginate: defaultPaginate, // 分页数据
            showDialog: false, // 是否显示 添加编辑窗口
            isEdit: false, // 是否修改
            params: {}, // http 请求参数
            paramsRules: ParamsRules, // 参数校验
            tableRow: null, // 单选选择的行内容
            tableRows: [], // 多选选择的行内容
            authGroupList: [], // 菜单权限组列表
            selectAuthGroup: null, // 选择的菜单权限组
            search: { auth_group_id: "" }, // 查询条件
            rolesList: [], // 权限角色列表
            rolesAllList: [],
            accountRow: null, // 选择的用户账号
        });
        // 获取菜单权限组
        function getAuthGroupList(data: any[]) {
            state.authGroupList = data;
        }
        // 选择 菜单权限组
        function changeAuthGroup(val: any) {
            state.dataList = [];
            state.selectAuthGroup = val;
            state.tableRow = null;
            state.tableRows = [];
            pTable.value.clearSelect();
            if (val != null) {
                state.search.auth_group_id = val.id;
                getRolesList(val.id);
            } else {
                state.search.auth_group_id = "";
            }
            getList();
        }
        // 获取权限id对应的名称
        function getRolesLabel(roles: any): string[] {
            const label: string[] = [];
            if (
                !utils.empty(roles) &&
                !utils.empty(state.rolesAllList) &&
                roles instanceof Array
            ) {
                const roleaMap: Map<string, string> = new Map<string, string>();
                for (const item of state.rolesAllList) {
                    roleaMap.set(item.id, item.role_name);
                }
                for (const item of roles) {
                    const str = roleaMap.get(item);
                    if (str !== undefined) {
                        label.push(str);
                    }
                }
            }
            return label;
        }
        // 添加 修改时 选择 菜单权限组
        function selectAuthFGroup(id: string) {
            state.params.roles = [];
            getRolesList(id);
        }
        // 选择用户账号事件
        function changeAccount(val: any) {
            state.accountRow = val;
        }
        // 获取全部权限角色内容
        function getAllRolesList() {
            http.Get(`/roles`, { auth_group_id: "" })
                .then((data) => {
                    state.rolesAllList = data;
                })
                .catch((err) => false);
        }
        // 获取权限角色内容
        function getRolesList(id: string) {
            http.Get(`/roles`, { auth_group_id: id })
                .then((data) => {
                    state.rolesList = data;
                })
                .catch((err) => false);
        }
        // 单击选中
        function rowClick(val: any) {
            state.tableRow = val.row;
        }
        // 取消选中
        function rowClear() {
            state.tableRow = null;
        }
        // 关闭添加修改窗口
        function dialogClose() {
            state.showDialog = false;
            state.params = {};
            state.accountRow = null;
            state.isEdit = false;
        }
        // 多选时触发
        function selectionChange(val: any[]): void {
            state.tableRows = val;
        }
        // 显示添加
        function showAdd() {
            state.params = {
                auth_group_id: state.selectAuthGroup.id,
                roles: [],
            };
            state.isEdit = false;
            state.showDialog = true;
        }
        // 获取内容
        function getList() {
            state.loading = true;
            state.dataList = [];
            http.Get(
                `/users/${state.paginate.page_size}/${state.paginate.page}`,
                state.search
            )
                .then((data) => {
                    state.dataList = data.data;
                    state.paginate = data.paginate;
                    state.loading = false;
                })
                .catch((err) => (state.loading = false));
        }
        // 添加
        function add() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Post("/users", state.params)
                        .then((data) => {
                            const userInfo = {
                                account: state.accountRow,
                                user: data,
                            };
                            if (utils.empty(state.dataList)) {
                                state.dataList = [userInfo];
                            } else {
                                state.dataList.unshift(userInfo);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        // 显示修改
        function showEdit() {
            if (state.tableRow == null) {
                message.error("请选择要修改的用户");
                return;
            }
            state.accountRow = state.tableRow.account;

            state.params.auth_group_id = state.tableRow.user.auth_group_id;
            if (utils.empty(state.tableRow.user.roles)) {
                state.params.roles = [];
            } else {
                state.params.roles = utils.CopyNewObject(state.tableRow.user.roles);
            }
            state.params.remarks = state.tableRow.user.remarks;
            state.params.uid = state.tableRow.user.uid;
            state.params.version = state.tableRow.user.version;

            state.isEdit = true;
            state.showDialog = true;
        }
        // 修改
        function edit() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Put("/users", state.params)
                        .then((data) => {
                            const userInfo = {
                                account: state.accountRow,
                                user: data,
                            };
                            const index = state.dataList.findIndex(
                                (item) => item.user.uid === data.uid
                            );
                            if (index >= 0) {
                                state.dataList.splice(index, 1, userInfo);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        // 删除
        function del() {
            const ids: string[] = [];
            if (state.tableRows.length === 0) {
                if (state.tableRow == null) {
                    message.error("请选择要删除的用户");
                    return;
                } else {
                    ids.push(state.tableRow.user.uid);
                }
            }
            state.tableRows.forEach((item) => {
                ids.push(item.user.uid);
            });
            message.loadingShow("删除中");
            http.Delete("/users", { ids })
                .then((data) => {
                    ids.forEach((uid) => {
                        const index = state.dataList.findIndex(
                            (item) => item.user.uid === uid
                        );
                        if (index >= 0) {
                            state.dataList.splice(index, 1);
                        }
                        state.tableRows = [];
                    });
                })
                .catch((err) => "");
        }
        onMounted(() => {
            getAllRolesList();
        });
        return {
            UIAuth,
            bodySize,
            utils,
            ...toRefs(state),
            getAccountLabel,
            accountType,
            pTable,
            elForm,
            getAuthGroupList,
            changeAuthGroup,
            getRolesLabel,
            selectAuthFGroup,
            changeAccount,
            getRolesList,
            rowClick,
            rowClear,
            dialogClose,
            selectionChange,
            showAdd,
            getList,
            add,
            showEdit,
            edit,
            del,
            getTitle: computed(() => state.isEdit ? '正在修改账号为【' + state.accountRow.account + '】的用户' : '添加用户')
        };
    },
});
</script>


<style scoped lang="scss">
.users {
    display: flex;
    & > div {
        &:first-child {
            width: 200px;
        }
        &:last-child {
            margin-left: 10px;
            width: calc(100% - 210px);
        }
    }
    &-roles-list {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        & > div {
            background-color: #ce5afb;
            color: #ffffff;
            border-radius: 4px;
            font-size: 12px;
            padding: 2px 5px;
            margin-bottom: 3px;
            margin-right: 3px;
        }
    }
}
</style>